package com.yanchangapp.ui.activity.purchase.contract;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.luck.picture.lib.tools.ScreenUtils;
import com.yanchangapp.PsCreateListAdapter;
import com.yanchangapp.R;
import com.yanchangapp.adapter.SupplierAdapter;
import com.yanchangapp.commom.LoadingType;
import com.yanchangapp.model.bean.CnProductBean;
import com.yanchangapp.model.bean.ProductExtractBean;
import com.yanchangapp.model.bean.SupplierBean;
import com.yanchangapp.model.cache.UserCache;
import com.yanchangapp.ui.activity.purchase.ProductNormalExtActivity;
import com.yanchangapp.ui.presenter.ContractCreateAtPresenter;
import com.yanchangapp.ui.view.ContractCreateAtView;
import com.yanchangapp.util.CashierInputFilter;
import com.yanchangapp.widget.BottomDialog;
import com.yanchangapp.widget.GoodsPriceDialog;
import com.yanchangapp.widget.LikeContentDialog;
import com.yanchangapp.widget.SpannableMoney;
import com.yanchangapp.widget.GoodsNumDialog;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.util.formatter.BigDecimalUtils;
import com.zxl.baselib.util.time.TimeUtil;
import com.zxl.baselib.util.ui.ResHelper;
import com.zxl.baselib.util.ui.StatusBarHelper;
import com.zxl.baselib.util.window.KeyboardHelper;
import com.zzhoujay.markdown.parser.Line;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

import static com.zxl.baselib.util.ui.UIUtils.showToast;

/**
 * 新建采购合同活动...
 */
public class ContractCreateActivity extends BaseActivity<ContractCreateAtView, ContractCreateAtPresenter> implements ContractCreateAtView, PsCreateListAdapter.ITotalAmountChanged {
    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.vToolbarDivision)
    View vToolbarDivision;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.ibAddMenu)
    ImageButton ibAddMenu;
    @BindView(R.id.btnCreate)
    Button btnCreate;
    @BindView(R.id.tvProductSum)
    TextView tvProductSum;
    @BindView(R.id.linearBottom)
    RelativeLayout linearBottom;
    @BindView(R.id.tvSignTitle)
    TextView tvSignTitle;
    @BindView(R.id.ivSignArrow)
    ImageView ivSignArrow;
    @BindView(R.id.tvSignTime)
    TextView tvSignTime;
    @BindView(R.id.rlSignTime)
    RelativeLayout rlSignTime;
    @BindView(R.id.tvBuyCompany)
    TextView tvBuyCompany;
    @BindView(R.id.tvAreaTitle)
    TextView tvAreaTitle;
    @BindView(R.id.ivAreaArrow)
    ImageView ivAreaArrow;
    @BindView(R.id.tvSupplierName)
    TextView tvSupplierName;
    @BindView(R.id.rlSupplier)
    RelativeLayout rlSupplier;
    @BindView(R.id.tvChooseProduct)
    TextView tvChooseProduct;
    @BindView(R.id.rvProductList)
    RecyclerView rvProductList;
    @BindView(R.id.tvProductEmpty)
    TextView tvProductEmpty;
    @BindView(R.id.tvTitleStartTime)
    TextView tvTitleStartTime;
    @BindView(R.id.ivStartArrow)
    ImageView ivStartArrow;
    @BindView(R.id.rlClause)
    RelativeLayout rlClause;

    private String signTime;
    private TimePickerView pvCustomTime;
    private BottomDialog mBottomSupplier;
    private SupplierAdapter mSupplierAdapter;
    private List<SupplierBean> mSupplierBeans = new ArrayList<>();
    private RecyclerView mRvSupplier;
    private LinearLayout mSupplierLlLoading,mSupplierLlEmpty;
    private RelativeLayout mSupplierRlError;
    private boolean mIsSupplierLoading = false;
    private int mSupplierPreIndex = -1;
    private int mSupplierNowIndex = -1;

    private String innerClause = "";
    private PsCreateListAdapter mPsCreateListAdapter;
    private List<ProductExtractBean> mExtractBeanList = new ArrayList<>();
    private double totalMoney;
    private EditText etNum;
    private Dialog mSingleDialog;
    private static final int REQUEST_PRODUCT_CODE = 0x0098;

    public static void show(Activity activity) {
        Intent intent = new Intent(activity, ContractCreateActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("result", Thread.currentThread().getName());
        if (resultCode == RESULT_OK){
            if (requestCode == ClauseEditActivity.CODE_QUERY_CLAUSE){
                innerClause = data.getStringExtra("data");
            }else if (requestCode == REQUEST_PRODUCT_CODE){
                if (tvProductEmpty.getVisibility() == View.VISIBLE){
                    tvProductEmpty.setVisibility(View.GONE);
                }

                if (rvProductList.getVisibility() == View.GONE){
                    rvProductList.setVisibility(View.VISIBLE);
                }
                mExtractBeanList.clear();
                mExtractBeanList.addAll((List<ProductExtractBean>)data.getExtras().getSerializable("data"));
                mPsCreateListAdapter.notifyDataSetChanged();
                setSumText();
            }
        }
    }

    @Override
    protected void init() {

    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_contract_create;
    }

    @Override
    protected ContractCreateAtPresenter createPresenter() {
        return new ContractCreateAtPresenter(this);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        // 设置标题
        tvToolbarTitle.setText("新建采购合同");
        initCustomTimePicker();
        setDefaultTime();
        setBuyerCompany();
        initAdapter();
        setSumText();
    }

    private void initAdapter() {
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);
        rvProductList.setHasFixedSize(true);
        rvProductList.setNestedScrollingEnabled(false);
        rvProductList.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, ScreenUtils.dip2px(this, 0.5f),
                ContextCompat.getColor(this, R.color.borderColorBase)));
        rvProductList.setLayoutManager(manager);
        mPsCreateListAdapter = new PsCreateListAdapter(R.layout.item_ps_create_list,mExtractBeanList);
        mPsCreateListAdapter.setITotalAmountChanged(this);
        // 设置adapter...
        rvProductList.setAdapter(mPsCreateListAdapter);
    }

    private void setBuyerCompany() {
        tvBuyCompany.setText(UserCache.getCompanyName());
    }

    private void setDefaultTime() {
        signTime = TimeUtil.date2String(getCalendar().getTime(),"yyyy-MM-dd HH:mm:ss");
        tvSignTime.setText(TimeUtil.getDayTime(signTime));
    }

    @Override
    protected void initData() {
    }


    private void initCustomTimePicker() {
        /**
         * @description
         *
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        Calendar nowCalendar = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2016, 1, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(nowCalendar.get(Calendar.YEAR)+1, 1, 1);
        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerBuilder(this, (date, v) -> {//选中事件回调
            String tvDay = TimeUtil.date2String(date,"yyyy-MM-dd");
            signTime = TimeUtil.date2String(date,"yyyy-MM-dd HH:mm:ss");
            tvSignTime.setText(tvDay);
        })
                .setTitleColor(ResHelper.getColor(R.color.colorPrimary))
                .setRangDate(startDate, endDate)
                .setContentTextSize(18)
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "时", "分", "秒")
                .setLineSpacingMultiplier(1.6f)
                .setTextXOffset(0, 0, 0, 40, 0, -40)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDecorView((ViewGroup) getWindow().getDecorView().findViewById(R.id.rootContract))
                .build();
    }

    @Override
    protected void initListener() {
        ivToolbarNavigation.setOnClickListener(v -> finish());
        // rl合同条款点击事件
        rlClause.setOnClickListener(v -> ClauseEditActivity.show(ContractCreateActivity.this,innerClause));

        rlSignTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyboardHelper.hideKeyboard(tvToolbarTitle);
                pvCustomTime.setDate(getCalendar());
                pvCustomTime.show();
            }
        });

        rlSupplier.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSupplierSheet();
            }
        });

        btnCreate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 检查数据并进行提交
                checkWithSubmit();
            }
        });

        tvChooseProduct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!tvChooseProduct.isSelected()){
                    showToast("请先选择供货单位");
                }else {
                    ProductNormalExtActivity.show(ContractCreateActivity.this,
                            mSupplierBeans.get(mSupplierNowIndex).getSupplierId(),mExtractBeanList);
                }
            }
        });

        mPsCreateListAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.ivDelete){
                mExtractBeanList.remove(position);
                mPsCreateListAdapter.notifyItemRemoved(position);
                mPsCreateListAdapter.notifyItemRangeChanged(position, mExtractBeanList.size() - position);
                setSumText();
                if (mExtractBeanList.size() == 0){
                    tvProductEmpty.setVisibility(View.VISIBLE);
                    rvProductList.setVisibility(View.GONE);
                }
            }else if (view.getId() == R.id.ivEdit || view.getId() == R.id.tvSinglePrice){
                showSetPriceDialog(ContractCreateActivity.this,position,mExtractBeanList.get(position).getPrice());
            }
        });
    }

    /**
     * 检查数据并进行创建提交
     */
    private void checkWithSubmit() {
        if (mSupplierNowIndex == -1){
            showToast("请选择供货方");
            return;
        }

        if (mExtractBeanList.size() == 0){
            showToast("请进行品种选择");
            return;
        }

        List<CnProductBean> mProductLists = new ArrayList<>();
        for (int i=0;i<mExtractBeanList.size();i++){
            ProductExtractBean bean = mExtractBeanList.get(i);
            mProductLists.add(new CnProductBean(
                    bean.getProductId(),bean.getProductNo(),bean.getSelectSize(),bean.getPrice(),
                    bean.getPrice() * bean.getSelectSize()));
        }
        mPresenter.createContract(signTime,mSupplierBeans.get(mSupplierNowIndex).getSupplierId(),
                totalMoney,mProductLists,innerClause);
    }

    private void showSetPriceDialog(Context context, int position, double price) {
        mSingleDialog = new GoodsPriceDialog.Builder(context)
                .setPrice(price)
                .setEnsureListener(new GoodsPriceDialog.PriceEnsureListener() {
                    @Override
                    public void onEnsureClick(double _price) {
                        mExtractBeanList.get(position).setPrice(_price);
                        mPsCreateListAdapter.notifyItemChanged(position);
                        setSumText();
                        mSingleDialog.dismiss();
                    }
                }).build();
        mSingleDialog.show();
    }

    private Calendar getCalendar(){
        // 判断时间是否为空...
        Calendar instance  = Calendar.getInstance();
        if (TextUtils.isEmpty(signTime)){
            // 如果是空的话 默认显示的是当前的时间...
            instance.set(Calendar.HOUR_OF_DAY,0);
            instance.set(Calendar.MINUTE,0);
            instance.set(Calendar.SECOND,0);
        }else {
            Date date = TimeUtil.string2Date(signTime, "yyyy-MM-dd HH:mm:ss");
            instance.setTime(date);
        }
        return  instance;
    }

    /**
     * 加载供货单位sheet...
     */
    private void showSupplierSheet(){
        if (mBottomSupplier == null){
            mBottomSupplier = new BottomDialog(this,0,true);
            View view = LayoutInflater.from(this).inflate(R.layout.bottom_cangku_area, null, false);
            mBottomSupplier.setContentView(view);
            // 设置背景为透明色 那么白色的就能呈现出来了
            mBottomSupplier.getDelegate().findViewById(android.support.design.R.id.design_bottom_sheet)
                    .setBackgroundColor(getResources().getColor(android.R.color.transparent));
            mRvSupplier = view.findViewById(R.id.rvWareHouse);
            mSupplierLlEmpty = view.findViewById(R.id.llEmpty);
            mSupplierLlLoading = view.findViewById(R.id.llLoading);
            mSupplierRlError = view.findViewById(R.id.rlErrorNetwork);
            TextView mTvWareRefresh = view.findViewById(R.id.btnNextRefresh);
            TextView tvToolbarTitle = view.findViewById(R.id.tvToolbarTitle);
            tvToolbarTitle.setText("选择供货单位");
            view.findViewById(R.id.closeBottom).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mBottomSupplier.hide();
                }
            });
            mRvSupplier.addItemDecoration(new RecycleViewDivider(
                    this, LinearLayoutManager.HORIZONTAL, ScreenUtils.dip2px(this,0.5f), ContextCompat.getColor(this, R.color.borderColorBase)));
            mRvSupplier.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
            mSupplierAdapter = new SupplierAdapter(R.layout.item_checkbox_text,mSupplierBeans);
            mSupplierAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                    if (mSupplierNowIndex == i){
                        // 如果相等直接关闭
                        mBottomSupplier.hide();
                        return;
                    }
                    mSupplierPreIndex = mSupplierNowIndex;
                    if (mSupplierPreIndex != -1){
                        mSupplierBeans.get(mSupplierPreIndex).setChecked(false);
                        mSupplierAdapter.notifyItemChanged(mSupplierPreIndex);
                    }
                    mSupplierNowIndex = i;
                    mSupplierBeans.get(mSupplierNowIndex).setChecked(true);
                    // 设置变化
                    mSupplierAdapter.notifyItemChanged(mSupplierNowIndex);
                    // 设置仓库地址...
                    tvSupplierName.setText(mSupplierBeans.get(mSupplierNowIndex).getSupplierName());
                    mBottomSupplier.hide();
                    // 设置选这品种可见
                    setAddProductEnable();
                    resetProductsWithRefresh();
                }
            });
            mTvWareRefresh.setOnClickListener(v -> loadSupplierData());
            // 设置Adapter
            mRvSupplier.setAdapter(mSupplierAdapter);
        }
        // 加载数据
        loadSupplierData();
        // 进行数据加载
        if (!isFinishing()){
            mBottomSupplier.show();
        }
    }

    /**
     * 重置品种选择
     */
    private void resetProductsWithRefresh() {
        mExtractBeanList.clear();
        //设置变化....
        mPsCreateListAdapter.notifyDataSetChanged();
        setSumText();
        if (mExtractBeanList.size() == 0){
            tvProductEmpty.setVisibility(View.VISIBLE);
            rvProductList.setVisibility(View.GONE);
        }
    }

    private double calculateNum(){
        double sum = 0;
        for (int i=0;i<mExtractBeanList.size();i++){
            ProductExtractBean bean = mExtractBeanList.get(i);
            sum += bean.getPrice() * bean.getSelectSize();
        }
        totalMoney = sum;
        return sum;
    }

    private void setSumText(){
        String totalMoney = BigDecimalUtils.keep2Decimal(calculateNum());
        int len = totalMoney.length();
        SpannableString spannableString = new SpannableString(ResHelper.getString(R.string.down_order_sum,
                String.valueOf(mExtractBeanList.size()),totalMoney));
        int totalLength = spannableString.length();
        spannableString.setSpan(new SpannableMoney(this),
                totalLength-len-1,totalLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvProductSum.setText(spannableString);
    }

    private void setAddProductEnable(){
        if (!tvChooseProduct.isSelected()){
            tvChooseProduct.setSelected(true);
        }
    }

    private void loadSupplierData(){
        if (!mIsSupplierLoading){
            setSupplierState(LoadingType.LOADING);
            mPresenter.loadSupplierData();
        }
    }

    private void setSupplierState(LoadingType loadingType){
        switch (loadingType){
            case SUCCESS:
                if (mRvSupplier.getVisibility() == View.GONE){
                    mRvSupplier.setVisibility(View.VISIBLE);
                }
                if (mSupplierRlError.getVisibility() == View.VISIBLE){
                    mSupplierRlError.setVisibility(View.GONE);
                }
                if (mSupplierLlLoading.getVisibility() == View.VISIBLE){
                    mSupplierLlLoading.setVisibility(View.GONE);
                }
                if (mSupplierLlEmpty.getVisibility() == View.VISIBLE){
                    mSupplierLlEmpty.setVisibility(View.GONE);
                }
                break;
            case LOADING:
                if (mRvSupplier.getVisibility() == View.VISIBLE){
                    mRvSupplier.setVisibility(View.GONE);
                }
                if (mSupplierRlError.getVisibility() == View.VISIBLE){
                    mSupplierRlError.setVisibility(View.GONE);
                }
                if (mSupplierLlLoading.getVisibility() == View.GONE){
                    mSupplierLlLoading.setVisibility(View.VISIBLE);
                }
                if (mSupplierLlEmpty.getVisibility() == View.VISIBLE){
                    mSupplierLlEmpty.setVisibility(View.GONE);
                }
                break;
            case EMPTY:
                if (mRvSupplier.getVisibility() == View.VISIBLE){
                    mRvSupplier.setVisibility(View.GONE);
                }
                if (mSupplierRlError.getVisibility() == View.VISIBLE){
                    mSupplierRlError.setVisibility(View.GONE);
                }
                if (mSupplierLlLoading.getVisibility() == View.VISIBLE){
                    mSupplierLlLoading.setVisibility(View.GONE);
                }
                if (mSupplierLlEmpty.getVisibility() == View.GONE){
                    mSupplierLlEmpty.setVisibility(View.VISIBLE);
                }
                break;
            case ERROR:
                if (mRvSupplier.getVisibility() == View.VISIBLE){
                    mRvSupplier.setVisibility(View.GONE);
                }
                if (mSupplierRlError.getVisibility() == View.GONE){
                    mSupplierRlError.setVisibility(View.VISIBLE);
                }
                if (mSupplierLlLoading.getVisibility() == View.VISIBLE){
                    mSupplierLlLoading.setVisibility(View.GONE);
                }
                if (mSupplierLlEmpty.getVisibility() == View.VISIBLE){
                    mSupplierLlEmpty.setVisibility(View.GONE);
                }
                break;
        }
    }


    @Override
    public void querySupplierFailure(String err) {
        setSupplierState(LoadingType.ERROR);
        mIsSupplierLoading = false;
        showToast(err);
    }

    @Override
    public void querySupplierSuccess(List<SupplierBean> mSupplierBeanList) {
        mIsSupplierLoading = true;
        if (mSupplierBeanList == null || mSupplierBeanList.size() == 0){
            // 数据为空的情况
            setSupplierState(LoadingType.EMPTY);
        }else {
            setSupplierState(LoadingType.SUCCESS);
            if (mSupplierAdapter != null && mBottomSupplier.isShowing()){
                mSupplierBeans.clear();
                mSupplierBeans.addAll(mSupplierBeanList);
                mSupplierAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (mBottomSupplier != null){
            mBottomSupplier.dismiss();
        }
        super.onDestroy();
    }

    @Override
    public void createContractSuccess(String contractID) {
        mRxManager.post(ContractListActivity.REFRESH_CONTRACT_LIST,true);
        ContractEnsureActivity.show(ContractCreateActivity.this,contractID);
    }

    @Override
    public void createContractFailure(String err) {
        showToast(err);
    }

    @Override
    public void justCalculateTotalPrice() {
        setSumText();
    }
}
